export const sendRequest = async <T>(
	config: OpenAPIConfig,
	options: ApiRequestOptions,
	url: string,
	body: any,
	formData: FormData | undefined,
	headers: Record<string, string>,
	onCancel: OnCancel,
	axiosClient: AxiosInstance
): Promise<AxiosResponse<T>> => {
	const source = axios.CancelToken.source();

	const requestConfig: AxiosRequestConfig = {
		url,
		headers,
		data: body ?? formData,
		method: options.method,
		withCredentials: config.WITH_CREDENTIALS,
		withXSRFToken: config.CREDENTIALS === 'include' ? config.WITH_CREDENTIALS : false,
		cancelToken: source.token,
	};

	onCancel(() => source.cancel('The user aborted a request.'));

	try {
		return await axiosClient.request(requestConfig);
	} catch (error) {
		const axiosError = error as AxiosError<T>;
		if (axiosError.response) {
			return axiosError.response;
		}
		throw error;
	}
};
